package com.cskaoyan.util;

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.exception.WdValidationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * @author stone
 * @date 2022/10/13 22:28
 */
public class ValidationUtil {
    public static BaseRespVo getBaseRespVo(BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            String field = fieldError.getField();
            Object rejectedValue = fieldError.getRejectedValue();
            String defaultMessage = fieldError.getDefaultMessage();
            StringBuffer sb = new StringBuffer();
            String msg = sb.append("请求参数")
                    .append(field)
                    .append("传入的值")
                    .append(rejectedValue)
                    .append("有问题 -- > ")
                    .append(defaultMessage).toString();
            return BaseRespVo.invalidParameter(msg);
        }
        return null;
    }

    public static void valid(BindingResult bindingResult) throws WdValidationException {
        if (bindingResult.hasFieldErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            String field = fieldError.getField();
            Object rejectedValue = fieldError.getRejectedValue();
            String defaultMessage = fieldError.getDefaultMessage();
            StringBuffer sb = new StringBuffer();
            String msg = sb.append("请求参数")
                    .append(field)
                    .append("传入的值")
                    .append(rejectedValue)
                    .append("有问题 -- > ")
                    .append(defaultMessage).toString();
            // 没有通过校验的情况下应该响应校验失败对应的json，但是这个方法并没有return
            // 抛出异常 → 通过异常处理器响应Json
            throw new WdValidationException(msg);
        }
    }
}
